/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.utility;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 *
 * @author xyzhu
 */
public class FileOperation {
    public static int copyFile(File f1,File f2){
        
        try{
            int length=2097152;
            FileInputStream in = new FileInputStream(f1);
            FileOutputStream out = new FileOutputStream(f2);
            FileChannel inC = in.getChannel();
            FileChannel outC=out.getChannel();
            ByteBuffer b=null;
            while(true){
                 if(inC.position()==inC.size()){
                    inC.close();
                    outC.close();
                    return 1;
                 }
                 if((inC.size()-inC.position())<length){
                    length=(int)(inC.size()-inC.position());
                 }else{
                     length=2097152;
                 }
                 b=ByteBuffer.allocateDirect(length);
                 inC.read(b);
                 b.flip();
                 outC.write(b);
                 outC.force(false);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return 0;
    }
    
    public static boolean deleteFile(File f){
        if(!f.exists()){
            System.out.println("删除文件失败：文件不存在");
            return false;
        }else{
            f.delete();
        }
        return true;
    }
    
    
    public static boolean deleteFile(String fn){
        File f = new File(fn);
        return deleteFile(f);
    }
    
}
